<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.gxgyl.com All rights reserved.

// +----------------------------------------------------------------------
// | Author: Liuyu
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\shiyao;

use app\api\model\User as UserModel;
use app\api\service\User as UserService;
use app\common\model\shiyao\ProjectCenter as ProjectCenterModel;
use cores\exception\BaseException;
use think\facade\Db;

/**
 * 模型
 * Class
 * @package app\common\model
 */
class ProjectCenter extends ProjectCenterModel {
	/**
	 * 隐藏字段
	 * @var array
	 */
	protected $hidden = [
		'is_delete',
		'store_id',
		'create_time',
		'update_time',
	];

	/**
	 * 获取收货地址列表
	 * @return \think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws BaseException
	 */
	public function getList(array $params = []) {
		$user = UserService::getCurrentLoginUser();
		$userId = $user['user_id'];

		$filter = [];

		!empty($params['search']) && $filter[] = ['center_name|center_code', 'like', "%{$params['search']}%"];

		$role = json_decode($user['role'], true);

		//协助pm

		$pm = Db::name('shiyao_project_pm')->where('pm_id', $userId)->field('project_id')->select()->toArray();
		$projectIds = array_column($pm, 'project_id');

		if (in_array(10006, $role)) {
			//申办方管理员

			$filter[] = ['center.project_id', '=', $params['projectId']];
		} elseif (in_array(10009, $role)) {
			//申办方管理员

			$filter[] = ['center.project_id', '=', $params['projectId']];
		} else {

			//是否共享中心信息 -弃用
			// $project = Db::name('shiyao_project')->where('project_id', $params['projectId'])->find();

			// if ($project['is_share'] == 1) {
			// 	$filter[] = ['project_id', '=', $params['projectId']];
			// } else {
			// 	$filter[] = ['project_id', '=', $params['projectId']];
			// 	$filter[] = ['pm_id|pm_id_xiezhu', '=', $userId];
			// }

			//审批人员
			$centerIds = Db::name('shiyao_project_center_pm')
				->where('pm_id', $userId)
				->where('project_id', $params['projectId'])
				->group('center_id')->select()->toArray();
			$centerIds = array_column($centerIds, 'center_id');

			//自己添加的项目
			$pmcenter = Db::name('shiyao_project_center')->where('project_id', $params['projectId'])->where('pm_id', $userId)->field('id')->group('center_id')->select()->toArray();
			$centerIds2 = array_column($pmcenter, 'id');
			$newcenterIds = array_merge($centerIds, $centerIds2);

			if ($newcenterIds) {

				$filter[] = ['center.project_id', '=', $params['projectId']];
				$filter[] = ['center.id', 'in', $newcenterIds];
			} else {
				//为了返回空
				$filter[] = ['center.store_id', '=', 1];
			}

		}

		// 实例化新查询对象
		$query = $this->getNewQuery();

		$list = $query->alias('center')->with(['pi', 'crc', 'pm', 'pm2'])
			->where($filter)
			->where('is_delete', '=', 0)
			->order('center_code asc')
			->select()->toArray();
		foreach ($list as $key => $value) {
			if ($value['pm'] == null) {
				$list[$key]['pm'] = $value['pm2'];
			}
			$crc = array_column($value['crc'], 'name');
			$list[$key]['crc_label'] = implode(';', $crc);
			$count = Db::name('shiyao_project_pay_log')->alias('pay')
				->join('shiyao_project p', 'p.project_id=pay.project_id')
				->join('shiyao_project_center center', 'center.id=pay.center_id')
				->where('pay.pm_status', 0)
				->where('pay.pi_status', 1)
				->where($filter)
				->where('pay.center_id', $value['id'])
				->where('p.level', 2)
				->count();
			$list[$key]['is_wait'] = $count > 0 ? 1 : 0;

		}

		return $list;
	}

	/**
	 * 新增
	 * @param array $data
	 * @return mixed
	 * @throws BaseException
	 */
	public function add(array $data) {
		// 当前用户信息
		$user = UserService::getCurrentLoginUser(true);

		// 添加
		return $this->transaction(function () use ($user, $data) {

			//收录center

			$center = Db::name('shiyao_center')->where('center_name', $data['center_name'])->find();
			if ($center) {
				$centerId = $center['center_id'];
			} else {
				$centerData['center_name'] = $data['center_name'];
				$centerData['address'] = $data['address'];
				$centerData['store_id'] = $user['store_id'];
				$centerData['create_time'] = time();
				$centerId = Db::name('shiyao_center')->insertGetId($centerData);
			}

			$data = array_merge($data, [
				'center_id' => $centerId,
				'store_id' => self::$storeId,
			]);

			$data['pm_id'] = $user['user_id'];

			$this->save($data);

			//审批人

			foreach ($data['pmIds'] as $key => $pm) {
				$insertData['project_id'] = $data['project_id'];
				$insertData['center_id'] = $this['id'];

				$insertData['pm_id'] = $pm['value'];
				$insertData['create_time'] = time();
				$insertData['store_id'] = self::$storeId;
				Db::name('shiyao_project_center_pm')->insert($insertData);
			}

			// //新增PI账号
			// $UserModel->increased([$data['pi']], 1);

			// //新增CRC账号
			// $UserModel1 = new UserModel;
			// $UserModel1->increased($data['crcList'], 2);

			// 新增PI
			//$Pi = new PiModel;

			Pi::increased((int) $this['id'], $data['project_id'], $data['piList']); //2

			//新增CRC
			Crc::increased((int) $this['id'], $data['project_id'], $data['crcList']); //1

			return true;
		});
	}

	/**
	 * 编辑收货地址
	 * @param array $data
	 * @return bool
	 * @throws BaseException
	 */
	public function edit(array $data) {
		// 当前用户信息
		$user = UserService::getCurrentLoginUser(true);

		// 添加
		return $this->transaction(function () use ($user, $data) {

			// $data = array_merge($data, [
			// 	'pm_id' => $user['user_id'],
			// 	'store_id' => self::$storeId,
			// ]);
			// $this->save($data);

			//收录center

			$center = Db::name('shiyao_center')->where('center_name', $data['center_name'])->find();
			if ($center) {
				$centerId = $center['center_id'];
			} else {
				$centerData['center_name'] = $data['center_name'];
				$centerData['address'] = $data['address'];
				$centerData['store_id'] = $user['store_id'];
				$centerData['create_time'] = time();
				$centerId = Db::name('shiyao_center')->insertGetId($centerData);
			}

			$d_data['center_id'] = $centerId;
			$d_data['center_name'] = $data['center_name'];
			$d_data['center_code'] = $data['center_code'];

			$d_data['address'] = $data['address'];

			Db::name('shiyao_project_center')->where('id', $data['id'])->update($d_data);

			//审批人

			//删除
			Db::name('shiyao_project_center_pm')
				->where('center_id', $this['id'])->where('project_id', $data['project_id'])->delete();

			foreach ($data['pmIds'] as $key => $pm) {
				$insertData['project_id'] = $data['project_id'];
				$insertData['center_id'] = $this['id'];

				$insertData['pm_id'] = $pm['value'];
				$insertData['create_time'] = time();
				$insertData['store_id'] = self::$storeId;
				Db::name('shiyao_project_center_pm')->insert($insertData);
			}

			// 新增PI
			Pi::increased((int) $this['id'], $data['project_id'], $data['piList']); //2

			//新增CRC
			Crc::increased((int) $this['id'], $data['project_id'], $data['crcList']); //1

			return true;
		});
	}

	/**
	 * 删除
	 * @return bool
	 * @throws BaseException
	 */
	public function remove() {
		// 查询当前是否为默认地址
		$user = UserService::getCurrentLoginUser(true);
		// 清空默认地址
		if ($user['address_id'] == $this['address_id']) {
			UserModel::updateBase(['address_id' => 0], ['user_id' => $this['user_id']]);
		}
		// 标记为已删除
		return $this->save(['is_delete' => 1]);
	}

	public function state() {

		return $this->save(['status' => 2]);
	}

	/**
	 *详情
	 * @param int $addressId
	 * @return UserAddress|array|null
	 * @throws BaseException
	 */
	public static function detail(int $CenterId) {
		$userId = UserService::getCurrentLoginUserId();
		$detail = self::get(['id' => $CenterId], ['project', 'pi.pay', 'crc.pay']);

		if (empty($detail)) {
			throwError('未找到该项目');
		}
		$pms = Db::name('shiyao_project_center_pm')->where('center_id', $CenterId)->select()->toArray();
		if ($pms) {

			$detail['pms'] = array_column($pms, 'pm_id');
		}
		return $detail;
	}
}
